import numpy as np
import os
import sys
import librosa
import matplotlib.pyplot as plt
from python_ai.common.xcommon import *
import soundfile as sf

BASE_DIR, FILE_NAME = os.path.split(__file__)
path = '../../../../large_data/audio/zsn-stop1.wav'
AUDIO_PATH = os.path.join(BASE_DIR, path)
SAVE_DIR = os.path.join(BASE_DIR, '_save', FILE_NAME)

spr = 2
spc = 2
spn = 0
plt.figure(figsize=[12, 6])

y, sr = librosa.load(AUDIO_PATH, sr=None, res_type='kaiser_fast')


def process_y(y, sr):
    global spn
    print_numpy_ndarray_info(y, 'y')
    spn += 1
    plt.subplot(spr, spc, spn)
    plt.plot(y)

    M = librosa.feature.mfcc(y, sr, n_mfcc=100)
    print_numpy_ndarray_info(M, 'M')
    m_mean = M.mean(axis=0)
    print_numpy_ndarray_info(m_mean, 'm_mean')
    spn += 1
    plt.subplot(spr, spc, spn)
    plt.plot(m_mean)


def save_y(y, sr, path):
    """
    librosa.output was removed in librosa version 0.8.0.
    This is documented in their changelog. So the most likely reason for your issue is that you are using this new
    version of librosa (and not version 0.6.x). You can verify by doing print(librosa.__version__).

    With moden librosa, you should instead use soundfile.write to write audio output.

    :param y:
    :param sr:
    :param path:
    :return:
    """
    os.makedirs(os.path.split(path)[0], exist_ok=True)
    sf.write(path, y, sr)


process_y(y, sr)
save_y(y, sr, os.path.join(SAVE_DIR, 'ori.wav'))

sep('pre-emphasized')
y = np.append(y[0:1], y[1:] - y[:-1] * 0.97)
process_y(y, sr)
save_y(y, sr, os.path.join(SAVE_DIR, 'pre_emphasized.wav'))

plt.show()
